package com.xczz.service.impl;

import com.xczz.common.constant.UserConstants;
import com.xczz.common.result.TableDataInfo;
import com.xczz.model.SysUser;
import com.xczz.model.vo.SysUserVO;
import com.xczz.service.SysUserService;
import com.xczz.repository.SysUserRepository;
import com.xczz.utils.BeanUtils;
import com.xczz.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserRepository sysUserRepository;

    @Override
    public List<SysUser> getAllUsers() {
        return sysUserRepository.findAll();
    }

    @Override
    public Optional<SysUser> getUserById(Long userId) {
        return sysUserRepository.findById(userId);
    }

    @Override
    public SysUser createUser(SysUser user) {
        return sysUserRepository.save(user);
    }

    @Override
    public SysUser updateUser(Long userId, SysUser user) {
        user.setUserId(userId); // 确保ID一致
        return sysUserRepository.save(user);
    }

    @Override
    public void deleteUser(Long userId) {
        sysUserRepository.deleteById(userId);
    }

    @Override
    @Transactional
    public int deleteUserByIds(Long[] userIds){
        return sysUserRepository.deleteUserByIds(userIds);
    }
    @Override
    public String checkUserNameUnique(String userName) {
        SysUser sysUserEntity=new SysUser();
        sysUserEntity.setUserName(userName);
        return count(sysUserEntity);
    }

    @Override
    public String checkPhoneUnique(SysUserVO userInfo) {
        SysUser user=new SysUser();
        BeanUtils.copyProperties(userInfo,user);
        return checkUnique(user);
    }

    @Override
    public String checkEmailUnique(SysUserVO userInfo) {
        SysUser user=new SysUser();
        BeanUtils.copyProperties(userInfo,user);
        return checkUnique(user);
    }

    public String count(SysUser sysuser){
        Example<SysUser> example=Example.of(sysuser);
        long count=sysUserRepository.count(example);
        if(count>0){
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    public String checkUnique(SysUser user){
        Long userId= StringUtils.isNull(user.getUserId())?-1L:user.getUserId();
        Example<SysUser> example= Example.of(user);
        SysUser info=findOne(example);
        if(StringUtils.isNotNull(info)&&info.getUserId().longValue()!=userId.longValue()){
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    public SysUser findOne(Example<SysUser> example){
        List<SysUser> list=sysUserRepository.findAll(example, PageRequest.of(0,1)).toList();
        if(list.isEmpty()){
            return null;
        }
        return list.get(0);
    }
    @Transactional
    public boolean insertUser(SysUserVO user){
        SysUser sysUser=new SysUser();
        BeanUtils.copyProperties(user,sysUser);
        sysUser.setDelFlag("0");
        sysUserRepository.save(sysUser);
        user.setUserId(sysUser.getUserId());
        insertUserRole(user);
        return null!=sysUser.getUserId();
    }

    @Transactional
    public int insertUserRole(SysUserVO user){
        Long[] roles=user.getRoleIds();
        if(StringUtils.isNull(roles)||roles.length==0){
            return 0;
        }
        Long[] userIds=new Long[roles.length];
        Arrays.fill(userIds,user.getUserId());
        return sysUserRepository.batchInsertUserRole(userIds,roles);
    }

    public TableDataInfo selectUserList(SysUserVO user, Pageable page){
        SysUser sysUser=new SysUser();
        BeanUtils.copyPropertiesIgnoreEmpty(user,sysUser);
        sysUser.setDelFlag("0");
        ExampleMatcher exampleMatcher= ExampleMatcher.matching()
                .withMatcher("userName",ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("phonenumber",ExampleMatcher.GenericPropertyMatchers.contains());
        Example<SysUser> example=Example.of(sysUser,exampleMatcher);
        Page<SysUser> rs=sysUserRepository.findAll(example,page);
        return TableDataInfo.success(rs.toList(),rs.getTotalElements());
    }

    @Override
    @Transactional
    public boolean updateUser(SysUserVO user){
        Long userId=user.getUserId();
        Optional<SysUser> op=sysUserRepository.findById(userId);
        if(!op.isPresent()){
            return false;
        }
        sysUserRepository.deleteUserRoleByUserId(userId);
        SysUser sysUser=op.get();
        BeanUtils.copyPropertiesIgnoreNull(user,sysUser);
        sysUserRepository.save(sysUser);
        insertUserRole(user);
        return null!=sysUser.getUserId();
    }

    @Override
    public SysUser selectUserById(Long userId){
        SysUser sysuser=new SysUser();
        sysuser.setUserId(userId);
        sysuser.setDelFlag("0");
        return sysUserRepository.findOne(Example.of(sysuser)).get();
    }

    @Override
    public SysUser selectUserByUserName(String userName){
        SysUser sysuser=new SysUser();
        sysuser.setUserName(userName);
        sysuser.setDelFlag("0");
        Example<SysUser> example=Example.of(sysuser);
        return findOne(example);
    }
}
